package cn.itcast.controller;

import cn.itcast.constant.MessageConstant;
import cn.itcast.entity.Result;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;
import java.util.Map;


@RequestMapping(path = "/sms")
@RestController
public class SmsController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 发送验证码
     * @param map
     * @return
     */
    @PostMapping("/sendLoginCode")
    public Result sendLoginCode(@RequestParam Map<String, String> map) {
        String code = "123123";
        try {
            Config config = new Config()
                    .setAccessKeyId("LTAI5tHLKGSXAC7fuGgRJktH")
                    .setAccessKeySecret("rRTJlzc04PlOiFjj552dA4ejDuRPio");
            // 访问的域名
            config.endpoint = "dysmsapi.aliyuncs.com";
            Client client = new Client(config);

            SendSmsRequest sendSmsRequest = new SendSmsRequest();
            sendSmsRequest.setPhoneNumbers(map.get("phone"));
            sendSmsRequest.setSignName("传智健康");
            sendSmsRequest.setTemplateCode("SMS_186613739");
            sendSmsRequest.setTemplateParam("{\"code\":\"" + code + "\"}");

            // 复制代码运行请自行打印 API 的返回值
            SendSmsResponse response = client.sendSms(sendSmsRequest);
            if ("OK".equals(response.getBody().getCode())) {
                System.out.println("验证码发送成功");
            }
            System.out.println(response.getBody().getMessage());
        } catch (Exception e) {
            e.printStackTrace();
        }
        redisTemplate.opsForValue().set("CHECK_CODE_" + map.get("phone"), code,Duration.ofMinutes(5));
        System.out.println(redisTemplate.opsForValue().get("CHECK_CODE_" + map.get("phone")));
        return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS,null);
    }
}
